<template>
	<view class="bg">
		<view class="qrcode_view">
			<canvas canvas-id="qrcode" v-show="qrShow" style="width: 300rpx;margin: 0 auto;" />
			<view class="upload" v-show="qrShow" @click="uploadQrcode">
				下载二维码
			</view>
		</view>
		<view class="qrcode_inout">
			<textarea placeholder="请输入文本或网址..." v-model="text"></textarea>
			<button @click="createQrcode">生成二维码</button>
		</view>
	</view>
</template>

<script>
	import uQRCode from '../../static/js/uqrcode.js';
	export default {
		data() {
			return {
				text: '', // 文本或网址
				qrShow: false,
			}
		},
		onLoad() {
			// 加载分享菜单
			this.loadingShareMenu();
		},
		methods: {
			// 生成二维码
			creatQrCode() {
				this.qrShow = true
				uQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text: this.text,
					size: 150,
					margin: 0,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					errorCorrectLevel: uQRCode.errorCorrectLevel.H,
					success: res => {}
				})
			},
			// 点击生成按钮
			createQrcode() {
				if (this.text == '') {
					uni.showToast({ //显示对话框
						title: "请输入文本",
						icon: 'none',
						duration: 1000,
					})
				} else {
					this.creatQrCode(this.text) //调用二维码方法
					this.text = '';
				}
			},
			// 点击下载二维码，将二维码图片保存到手机
			uploadQrcode() {
				setTimeout(() => {
					wx.canvasToTempFilePath({
						canvasId: 'myCanvas',
						success: function(res) {
							console.log("save ok canvasToTempFilePath", res)
							var tempFilePath = res.tempFilePath;
							wx.saveImageToPhotosAlbum({
								filePath: tempFilePath,
								success(res) {
									console.log('saveImageToPhotosAlbum', res);
									wx.showToast({
										title: '已保存到相册',
										icon: 'success',
										duration: 2000
									})
								}
							})
						},
						fail: function(res) {
							console.log(res);
						}
					});
				}, 500)
			},
			
			// 加载分享菜单
			loadingShareMenu() {
				wx.showShareMenu({
					withShareTicket: true,
					//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
					menus: ["shareAppMessage", "shareTimeline"]
				})
			},
		}
	}
</script>

<style lang="less" scoped>
	@import url('../../static/css/basic.css');

	.qrcode_view {
		width: 100%;
		padding-top: 30px;
		display: flex;
		justify-content: space-evenly;
		align-items: flex-end;

		.upload {
			width: 200rpx;
			font-size: 14px;
			color: #00c7c7;
			text-decoration: #dbd9ff;
		}
	}

	.qrcode_inout {
		margin-top: 80px;

		textarea {
			width: 80%;
			height: 120px;
			background-color: #dbd9ff;
			margin-left: auto;
			margin-right: auto;
			border-radius: 10px;
			padding-left: 10px;
			padding-top: 10px;
		}

		button {
			margin-top: 50px;
			width: 100%;
			height: 60px;
			border-radius: 10px;
			color: #00ffff;
			font-size: 26px;
			letter-spacing: 2px;
			font-weight: 600;
			background-color: #ff557f;
			box-shadow: 2px 2px 4px #706f82;
		}
	}
</style>
